package com.mioto.ld.communication;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.mioto.ld.communication.mqtt.protocol.model.Message;
import com.mioto.ld.communication.mqtt.protocol.model.ReplyStatusEnum;
import com.mioto.ld.communication.mqtt.protocol.model.device.DeviceReplyPayload;
import com.mioto.ld.communication.websocket.model.SendCmdEnum;
import com.mioto.ld.communication.websocket.model.WsSendMessage;
import com.mioto.ld.communication.websocket.util.MessageSendUtil;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author mioto-qinxj
 * @date 2024/5/16
 * @desc websocket - mqtt通讯监听
 */
@Component
public class CommunicationListener {
    @Resource
    private CommunicationCache communicationCache;
    /*@Resource
    private DeviceOfflineProcess deviceOfflineProcess;*/

    @EventListener
    public void addListener(CommunicationEventSource source){
        Message message = source.getMessage();
        DeviceReplyPayload payload = (DeviceReplyPayload) message.getMessageBody().getPayload();
        boolean replyResult =  ObjectUtil.equal(payload.getStatusCode(), ReplyStatusEnum.DEVICE_REPLY_SUCCESS.getStatusCode());
        if (replyResult){
            String clientId = communicationCache.getClientId(message.getSn(),payload.getPtype());
            if (StrUtil.isNotEmpty(clientId)) {
                MessageSendUtil.send(clientId, new WsSendMessage(SendCmdEnum.CONTROL_SUCCESS));
            }
            //设备远程关机 -- 不做任何处理
            /** if (payload.getPower() == 0){
                deviceOfflineProcess.handler(message,false);
            }*/
        }
    }
}
